'use strict'

const { ApiController } = require('jax')
const helper = require('jax/app/utils/helper')
const dayjs = require('dayjs')

class Controller extends ApiController {
  // 门店列表
  async index() {
    const { ctx } = this
    const { helper } = ctx
    const { query } = ctx

    const { lng, lat } = ctx.query
    const maxDistance = 500

    const startDate = query.startDate || dayjs().format('YYYY-MM-DD')
    const endDate = query.endDate || dayjs().add(1, 'M').format('YYYY-MM-DD')

    const filter = {
      isOpen: true, // 在这里添加所有筛选条件
      // files: { $exists: true, $ne: [] }
    }

    // 关键字模糊查询
    if (query.keyword && !query.keyword == '') {
      const reg = new RegExp(helper.toMongoRegex(query.keyword, 'i'))
      filter.$or = [{ storeName: reg }, { address: reg }]
    }

    // 城市
    if (query.city && query.city != '') filter.city = query.city

    const stores = await ctx.model.Store.aggregate([
      {
        $geoNear: {
          near: {
            type: 'Point',
            coordinates: [parseFloat(lng), parseFloat(lat)],
          },
          distanceField: 'distance',
          // maxDistance, // 最大多少米
          spherical: true,
          key: 'location', // 明确指定地理空间索引字段
          query: filter,
        },
      },
      {
        $addFields: {
          distanceKm: { $divide: ['$distance', 1000] }, // 将米转换为公里
        },
      },
      {
        $sort: { distance: 1 }, // 按距离升序排序（近→远）
      },
      {
        $limit: 50, // 限制返回数量
      },
    ]).then((res) => {
      return res.map((item) => {
        item.distanceKm = item.distanceKm.toFixed(2)
        item.distance = item.distance.toFixed(2)
        item.id = item._id

        return helper.include(item, [
          'id',
          'storeName',
          'distanceKm',
          'openStartTime',
          'openEndTime',
          'cover',
          'address',
          'lng',
          'lat',
        ])
      })
    })

    await helper.queue(stores, async (item) => {
      const filter = {
        storeId: item.id,
        activityDate: {
          $gte: new Date(`${startDate} 00:00:00`),
          $lt: new Date(`${endDate} 23:59:59`),
        },
        isOpen: true,
      }

      await Promise.all([
        // 可预约数
        ctx.model.Activity.count({
          status: 0,
          ...filter,
        }).then((res) => {
          item.availableCount = res
        }),
        // 总数
        ctx.model.Activity.count(filter).then((res) => {
          item.activityCount = res
        }),
      ])
    })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: stores,
    }
  }

  // 门店详情
  async show() {
    const { ctx } = this
    const { helper } = ctx

    const storeId = ctx.params.id

    const store = await ctx.model.Store.findOne({
      _id: storeId,
      isOpen: true,
    })

    if (!store) throw '门店不存在'

    ctx.body = {
      code: 0,
      msg: 'success',
      data: helper.include(store, [
        'id',
        'storeName',
        'distanceKm',
        'openStartTime',
        'openEndTime',
        'cover',
        'address',
        'lng',
        'lat',
      ]),
    }
  }
}

module.exports = Controller
